Page({
  data: {
    userInfo: {},
    activeTab: 'recipes',
    recipeList: [], // 菜谱数据（含id）
    workList: [],   // 作品数据（含id）
    isLoggedIn: false,
    followCount: 0, // 关注数量
    fanCount: 0,    // 粉丝数量
    likesCount: 0   // 收到的赞数量
  },

  onlikes() {
    // 跳转“收到的赞列表”并传递当前用户ID
    this.gotoLikes();
  },

  onLoad() {
    this.checkLoginStatus();
  },

  onShow() {
    this.checkLoginStatus();
    this.loadUserData();      // 加载用户和菜谱数据
    this.loadWorkData();      // 加载作品数据
    this.loadFollowCount();   // 加载关注数量
    this.loadFanCount();      // 加载粉丝数量
    this.loadLikesCount();    // 加载收到的赞数量
  },

  // 检查登录状态
  checkLoginStatus() {
    const app = getApp();
    const isLoggedIn = app.isLoggedIn();

    this.setData({
      isLoggedIn: isLoggedIn,
      userInfo: app.globalData.userInfo || {},
      
    });

    if (!isLoggedIn) {
      wx.redirectTo({ url: '/pages/login/login' });
    }
  },

  // 加载关注数量
  loadFollowCount() {
    if (!this.data.isLoggedIn) return;

    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '未获取到用户ID', icon: 'none' });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/follow/count/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const followCount = res.data.data || 0;
          this.setData({ followCount, 'userInfo.following': followCount });
        } else {
          wx.showToast({ title: '获取关注数量失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('关注数量请求失败:', err);
        wx.showToast({ title: '关注数量加载失败', icon: 'none' });
      }
    });
  },

  // 加载粉丝数量
  loadFanCount() {
    if (!this.data.isLoggedIn) return;

    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '未获取到用户ID', icon: 'none' });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/follow/fan-count/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const fanCount = res.data.data || 0;
          this.setData({ fanCount, 'userInfo.followers': fanCount });
        } else {
          wx.showToast({ title: '获取粉丝数量失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('粉丝数量请求失败:', err);
        wx.showToast({ title: '粉丝数量加载失败', icon: 'none' });
      }
    });
  },

  // 加载收到的赞数量
  loadLikesCount() {
    if (!this.data.isLoggedIn) return;

    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '未获取到用户ID', icon: 'none' });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/likes/count/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (typeof res.data === 'number') {
          const likesCount = res.data || 0;
          this.setData({ likesCount, 'userInfo.likesReceived': likesCount });
        } else {
          wx.showToast({ title: '获取点赞数量失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('点赞数量请求失败:', err);
        wx.showToast({ title: '点赞数量加载失败', icon: 'none' });
      }
    });
  },

  // 加载用户和菜谱数据
  loadUserData() {
    if (!this.data.isLoggedIn) return;

    const that = this;
    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '未获取到用户ID', icon: 'none' });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/users/withRecipes/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      success(res) {
        if (res.data && res.data.code === 200 && res.data.data) {
          const userData = res.data.data;
          const formattedUser = {
            id: userData.id,
            name: userData.nickname || '用户',
           // avatar: userData.avatarUrl ? `http://localhost:8080${userData.avatarUrl}` : '/images/116.png',
            avatar: userData.avatarUrl 
  ? (userData.avatarUrl.startsWith('http') 
      ? userData.avatarUrl  // 若已为绝对路径，直接使用
      : `https://gzq123.oss-cn-beijing.aliyuncs.com/${userData.avatarUrl}`)  // 相对路径拼接
  : '/images/116.png',  // 默认图需确保路径正确
            gender: userData.sex === 1 ? '女' : '男',
            joinYear: userData.joinTime ? userData.joinTime.split('-')[0] : '',
            points: userData.totalPoint || 0,
            recipeCount: userData.recipesList?.length || 0,
            workCount: 0,
            isVip: userData.isVip === 1,
            vipExpireDate: userData.vipExpireTime ? new Date(userData.vipExpireTime).toLocaleDateString('zh-CN') : ''
          };

          const recipeList = userData.recipesList?.map(recipe => ({
            id: recipe.id,
            title: recipe.title || '未命名菜谱',
            imageUrl: recipe.coverUrl ? `https://gzq123.oss-cn-beijing.aliyuncs.com/${recipe.coverUrl}` : '/images/default-recipe.png',
            isVideo: recipe.mediaType === 2,
            introduction: recipe.introduction || '',
            createTime: recipe.createTime || ''
          })) || [];

          that.setData({ userInfo: formattedUser, recipeList: recipeList });
        } else {
          wx.showToast({ title: '菜谱数据获取失败', icon: 'none' });
        }
      },
      fail(err) {
        console.error('菜谱请求失败:', err);
        wx.showToast({ title: '菜谱加载失败', icon: 'none' });
      }
    });
  },

  // 加载作品数据
  loadWorkData() {
    if (!this.data.isLoggedIn) return;

    const that = this;
    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '未获取到用户ID', icon: 'none' });
      that.setData({ workList: [], 'userInfo.workCount': 0 });
      return;
    }

    wx.request({
      url: `http://localhost:8080/userr/users/withWorks/${userId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      success(res) {
        let workList = [];
        let workCount = 0;

        if (res.data && res.data.code === 200 && res.data.data) {
          const workData = res.data.data;
          const originWorks = Array.isArray(workData.worksList) ? workData.worksList : [];

          workList = originWorks.map(work => ({
            id: work.id || work.workId,
            title: work.title || '未命名作品',
            imageUrl: work.coverUrl || work.coverImg ? `https://gzq123.oss-cn-beijing.aliyuncs.com/${work.coverUrl || work.coverImg}` : '/images/default-work.png',
            isVideo: work.mediaType === 2,
            viewCount: work.viewCount || 0,
            createTime: work.createTime || ''
          }));

          workCount = workList.length;
        } else {
          wx.showToast({ title: '作品数据获取失败', icon: 'none' });
        }

        that.setData({ workList: workList, 'userInfo.workCount': workCount });
      },
      fail(err) {
        console.error('作品请求失败:', err);
        that.setData({ workList: [], 'userInfo.workCount': 0 });
        wx.showToast({ title: '作品加载失败', icon: 'none' });
      }
    });
  },

  // 积分点击
  onPointsTap() {
    wx.navigateTo({ url: '/my/pages/points-mall/points-mall' });
  },

  // 签到点击
  onCheckinTap() {
    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    // 跳转至签到详情页，并传递用户ID参数
    wx.navigateTo({
      url: `/my/pages/checkin-detail/checkin-detail?userId=${userId}`
    });
  },

  // 跳转关注列表（传递当前用户ID）
  gotoFollowed() {
    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/index/pages/followed/followed?userId=${userId}`, // 传递userId参数
    }).then(() => {
      setTimeout(() => this.loadFollowCount(), 500); // 返回后刷新数据
    });
  },

  // 跳转粉丝列表（传递当前用户ID）
  gotoFans() {
    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/index/pages/fans/fans?userId=${userId}`, // 传递userId参数
    }).then(() => {
      setTimeout(() => this.loadFanCount(), 500); // 返回后刷新数据
    });
  },

  // 跳转收到的赞列表（传递当前用户ID）
  gotoLikes() {
    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/my/pages/likes/likes?userId=${userId}`, // 传递userId参数
    }).then(() => {
      setTimeout(() => this.loadLikesCount(), 500); // 返回后刷新数据
    });
  },

  // 跳转收藏列表（传递当前用户ID）
  gotoCollections() {
    const app = getApp();
    const userId = app.globalData.userInfo?.id;
    if (!userId) {
      wx.showToast({ title: '用户ID无效', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: `/my/pages/collections/collections?userId=${userId}`, // 传递userId参数
    });
  },

  // // 跳转个人信息
  // gotoInformation() {
  //   wx.navigateTo({ url: '/my/pages/information/information' });
  // },

  // 设置按钮
  onSettings() {
    wx.navigateTo({ url: '/my/pages/settings/settings' });
  },

  // 激活会员
  onActivateVip() {
    wx.navigateTo({
      url: `/my/pages/membership/membership?points=${this.data.userInfo.points}`,
    });
  },

  // 标签切换
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },

  // 菜谱点击跳转
  onRecipeTap(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) {
      wx.showToast({ title: '菜谱ID无效', icon: 'none' });
      return;
    }
    wx.navigateTo({ url: `/index/pages/detail/detail?id=${id}` });
  },

  // 作品点击跳转
 // 作品点击跳转
 onWorkTap(e) {
  const workId = e.currentTarget.dataset.id;
  const app = getApp();
  const userId = app.globalData.userInfo?.id;
  console.log("userId",userId);
  console.log("workId:",workId);
  wx.navigateTo({
  url: `/find/pages/findDetail/findDetail?id=${workId}&authorId=${userId}`
  });
},


  // 分享功能
  onShareAppMessage() {
    return {
      title: `${this.data.userInfo.name}的个人主页`,
      path: '/pages/mine/mine',
      imageUrl: this.data.userInfo.avatar
    };
  },

  onShareTimeline() {
    return { title: `${this.data.userInfo.name}的个人主页` };
  }
});